package org.fing.edu.uy.esbadp.init;

import java.util.logging.Level;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.fing.edu.uy.esbadp.constants.EsbAdpPropertyConfig;
import org.fing.edu.uy.esbadp.core.registry.RegistryManager;
import org.fing.edu.uy.esbadp.logger.LoggerADP;
import org.fing.edu.uy.esbadp.modules.admMonitoring.AdmMonitoringThread;

public class InitializeEsbAdaptative implements ServletContextListener {
	
	private static java.util.logging.Logger logger = LoggerADP.getLogger(InitializeEsbAdaptative.class.getSimpleName());

	private AdmMonitoringThread admMonitoringThread = null;
	
	@Override
	public void contextDestroyed(ServletContextEvent context) {
		try {
			if(admMonitoringThread != null){
				admMonitoringThread.stopSafe();
			}
			EsbAdaptativeServicesManager.getInstance().unRegisterAll();
        } catch (Exception ex) {
        	logger.log(Level.SEVERE, "Exception in InitializeEngineMonitor..\n StackTarce.", ex);
        }
	}

	@Override
	public void contextInitialized(ServletContextEvent context) {
		 if ((admMonitoringThread == null) || (!admMonitoringThread.isAlive())) {	 
			 AdpConfigurationLoader adpConf = new AdpConfigurationLoader();
			 //Load config properties
			 adpConf.loadConfigProperties();	 
			 //Register adaptative actions
			 adpConf.registerAdpAction();
			 //Register adaptative service requirements
			 adpConf.registerAdpServiceRequirements();
			 //Register adaptative monitor Mechanism
			 adpConf.registerAdpMonitorMechanism();
			 //Register adaptative monitor Properties
			 adpConf.registerAdpMonitorProperties();
			 
			 EsbAdaptativeServicesManager.getInstance().registerAll();
			 
			 long timeSleep = Long.parseLong(RegistryManager.getInstance().getAdpConfigProperty(EsbAdpPropertyConfig.sleepTimeThreadAdmMonitor, "30000"));
			 admMonitoringThread = new AdmMonitoringThread(timeSleep);
			 admMonitoringThread.start();
			 
			 logger.info("The thread EngineMonitorThread was initialized...");
        }
	}

}
